import { axiosRequestAdapter } from "@alova/adapter-axios";
import { createAlova } from "alova";
import VueHook from "alova/vue";

import { TOKEN_KEY } from "@/config/constants";
import { PageRouteEnum } from "@/router/routes";
import { useUserStore } from "@/stores/user";
import { Feedback } from "@/utils/feedback";

import { createApis, mountApis, withConfigType } from "./createApis";

export interface MethodMeta {
    ignoreToken?: boolean; // 是否忽略token
    isDownload?: boolean; // 是否为下载请求
}

export const alovaInstance = createAlova({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    // requestAdapter: fetchAdapter(),
    requestAdapter: axiosRequestAdapter(),
    statesHook: VueHook,
    beforeRequest: method => {
        // 需要 token 的请求
        if (!method.meta?.ignoreToken) {
            method.config.headers = {
                Authorization: "Bearer " + localStorage.getItem(TOKEN_KEY)
            };
        }
    },
    responded: {
        // 请求成功的拦截器
        // 当使用 `alova/fetch` 请求适配器时，第一个参数接收Response对象
        // 第二个参数为当前请求的method实例，你可以用它同步请求前后的配置信息
        onSuccess: async (response, method) => {
            // 通过 http 状态码识别错误
            if (response.status >= 400) {
                console.log("response.statusText", response.statusText);
                Feedback.msgError(response.statusText);
                if (response.status === 401) {
                    useUserStore().logout();
                    window.location.href = PageRouteEnum.LOGIN;
                }
                throw new Error(response.statusText);
            }
            if (method.meta?.isDownload) {
                // return response.blob();
                return response;
            }
            // const res = await response.json();
            const res = response.data;

            // 通过业务状态码识别错误
            if (res.code < 200 || res.code > 300) {
                // 抛出错误或返回reject状态的Promise实例时，此请求将抛出错误
                console.log("res", res);
                const message = typeof res.msg === "string" ? res.msg : res.msg[0];
                Feedback.msgError(message);
                if (res.code === 401) {
                    useUserStore().logout();
                    window.location.href = PageRouteEnum.LOGIN;
                }
                throw new Error(res.msg);
            }

            return res;
        },
        onError: (err, _method) => {
            // 请求超时或网络错误
            Feedback.msgError(err.message);
        }
    }
});

export const $$userConfigMap = withConfigType({});

const Apis = createApis(alovaInstance, $$userConfigMap);

mountApis(Apis);

export default Apis;
